/*
 * CNetworkManager.h
 *
 *  Created on: 11.08.2011
 *      Author: kirill
 *      Copyright: LGPL
 */

#ifndef CNETWORKMANAGER_H_
#define CNETWORKMANAGER_H_

#include "CNetworkSpeaker.h"
#include "IConnection.h"
#include "Constants.h"
#include "BasicTypes.h"
#include "TThreadSafeQueue.h"
#include <string>
#include <vector>
#include <boost/intrusive/slist.hpp>
#include <boost/thread/thread.hpp>

static UINT RandNumber = 0;

/*
 *
 */
class CNetworkManager
{
	struct l_CONNECTION_DESCRIPTOR
	{
		bool           connected;
		bool		   checkConnection; // Uses for time critical connection checking
		IConnection   *connection;
	};
private:
	CNetworkSpeaker *networkSpeaker;
	l_CONNECTION_DESCRIPTOR Connections[MAX_PLAYERS_COUNT]; //contains all connections
	UINT maxConnectionCount;
	TThreadSafeQueue<STANDART_NETWORK_MESSAGE*> *incomeQueue;
	std::vector<STANDART_NETWORK_MESSAGE*> *outMessagesArray; //Messages will be give out

	bool allowConnections; // Enable/disable new connections to be establish
	volatile bool ReadingThreadAllow; //Uses for manage ProcessMessagesThread()

	void PrepareConnection( UINT MaxConnectionCount );
	void RunProcessMessages();
	void ProcessMessagesThread(); //Parses income queue and sends messages from income queue
	void ConnectionNotify( const BYTE ConnectionId, const bool Estabilished ); //Notify system about new connection
	void ConfirmConnection( const BYTE ConnectionId );
public:
	CNetworkManager();
	virtual ~CNetworkManager();
	virtual void CreateConnection( const char *IpAddress, const UINT FirstPort, const UINT LastPort );
	virtual void CreateConnection( const UINT FirstPort, const UINT LastPort, const UINT MaxConnectionCount = 0 );
	virtual void BreakConnection( const BYTE ConnectionId, const bool SendMessage );
	virtual void StopCreatingConnections();
	virtual void SendMessages( const std::vector<STANDART_NETWORK_MESSAGE*> &Messages );
	virtual std::vector<STANDART_NETWORK_MESSAGE*>* GetMessages();
	virtual BYTE ConnectionCreateCallback( IConnection* Connection, const UINT ConnectionID );// TODO ConnectionID BYTE
	virtual void TimerHandler( UINT TimerId );
};

#endif /* CNETWORKMANAGER_H_ */
